src/gcd.js
zzmq.dev@gmail.com[dev2]/mathkit[add-lcm-b-function-returns-least-common] / src / gcd.js
@ d0011d30
Download
Ladder Summary
- file Provides a `gcd` function that computes the greatest common divisor of two integers using the Euclidean algorithm, handling non‑numeric inputs by returning undefined, normalizing inputs to absolute truncated integers, and correctly returning 0 when both inputs are zero.
/**
* Computes the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
*
* @param {number} a - First integer.
* @param {number} b - Second integer.
* @returns {number} The GCD of a and b. Returns 0 if both inputs are 0.
*/
export function gcd(a, b) {
// Ensure inputs are numbers; if not, return undefined (consistent with other utilities)
if (typeof a !== "number" || typeof b !== "number") return undefined;
// Work with absolute integer values
a = Math.abs(Math.trunc(a));
b = Math.abs(Math.trunc(b));
// Euclidean algorithm
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}